<template>
	<view class="uni-container">
		<uni-popup ref="list_subjectpage" :mask-click="false" style="height: 70vh;overflow: scroll;">
			<view style="max-height: 70vh;overflow: scroll;">
				<list-subjectpage :mechanismId="id" @closepop="()=>$refs.list_subjectpage.close()">
				</list-subjectpage>
			</view>

		</uni-popup>

		<uni-popup ref="list_mechanism" :mask-click="false">
			<list-mechanism :mechanismId="id" @closepop="()=>$refs.list_mechanism.close()">
			</list-mechanism>
		</uni-popup>


		<uni-forms ref="form" :value="formData" validateTrigger="bind" label-position="top">
			<uni-forms-item name="name" label="机构昵称">
				<uni-easyinput v-model="formData.name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="parent_id" label="上级">
				<cu-select :localdata="mechanismList" v-model="formData.parent_id" @onSearch="fillterMech">
				</cu-select>
			</uni-forms-item>
			
			<uni-forms-item name="area" label="区域">
				<el-cascader  size="large" :options="cityRegion" v-model="formData.area">
				</el-cascader>
			</uni-forms-item>
			
			<uni-forms-item name="address" label="地址">
				<uni-easyinput v-model="formData.address"></uni-easyinput>
			</uni-forms-item>
			
			<uni-forms-item name="mobile" label="联系手机">
				<uni-easyinput v-model="formData.mobile"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="tel" label="座机">
				<uni-easyinput v-model="formData.tel"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="common" label="备注">
				<uni-easyinput v-model="formData.common" type="textarea" maxlength='-1'></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="note" label="负责人">
				<uni-easyinput v-model="formData.note"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="create_time" label="创建时间">
				<uni-datetime-picker return-type="timestamp" v-model="formData.create_time"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="end_time" label="授权结束日期">
				<uni-datetime-picker return-type="timestamp" v-model="formData.end_time"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="status" label="机构状态">
				<uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata">
				</uni-data-checkbox>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<button type="primary" class="uni-button" style="width: 100px;" @click="showJiAdmin(id)">管理员</button>
				<button type="primary" class="uni-button" style="width: 100px;" @click="showMechanism(id)">题库</button>
				<button type="warn" class="uni-button" style="width: 100px;" @click="deleteMec(id)">删除</button>
				<button class="uni-button" @click="close" style="width: 100px;">关闭</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '@/js_sdk/validator/mechanism.js';
	import ceSelect from '@/pages/mechanism/component/cuSelect.vue'
	
	
	import {
		regionDataPlus,
		CodeToText,
		TextToCode
	} from 'element-china-area-data'
	
	
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'mechanism';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		props: {
			id: ''
		},
		components: {
			'cu-select': ceSelect
		},
		emits: ['onClose'],
		data() {
			let formData = {
				"name": "",
				"parent_id": "",
				"mobile": "",
				"note": "",
				"create_time": null,
				"end_time": null,
				"status": 0,
				"update": null,
				"address":'',
				"area":[],
				"common": '',
				"tel": ''
			}
			return {
				cityRegion:regionDataPlus,
				cur_mechanism_id: '',
				formData,
				formOptions: {
					"status_localdata": [{
							"value": 0,
							"text": "欠费"
						},
						{
							"value": 1,
							"text": "正常"
						},
						{
							"value": 2,
							"text": "终止"
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				},
				copyList:[],
				mechanismList: []
			}
		},
		onLoad(e) {
			if (e.id) {
				this.formDataId = e.id
				this.getDetail(e.id)
			}
		},
		created() {
			if (this.id) {
				console.log(this.id)
				this.formDataId = this.id
				this.getDetail(this.id)
			}

		},
		mounted() {
			this.$refs.form.setRules(this.rules)
			this.getAllList()
		},
		onReady() {
			// this.$refs.form.setRules(this.rules)
			// this.getAllList()
		},
		methods: {
			fillterMech(e){
				console.log('e',e)
				if(e==''){
					this.mechanismList = this.copyList
					return 
				}
				let searchData = [] 
				for (let row of this.copyList) {
					if(row.text.indexOf(e)!=-1){
						searchData.push(row)
					}
				}
				if(searchData.length>0){
					this.mechanismList = searchData
				}
			},
			deleteMec(id){
				const self = this 
				uni.showModal({
					content:'是否删除?',
					title:"警告",
					success(res) {
						if(res.confirm){
							db.collection('mechanism')
							.where({
								_id:id
							})
							.remove().then((res)=>{
								console.log(res)
								uni.showToast({
									title:'删除成功',
									icon:"none",
									duration:2000
								})
								self.close()
								uni.$emit('refreshData')
							}).catch((e)=>{
								uni.showToast({
									title:e,
									icon:"none",
									duration:2000
								})
							})
						}
					}
				})
			},
			showMechanism(id) {
				console.log(this.cur_mechanism_id)
				this.cur_mechanism_id = id
				this.$refs.list_subjectpage.open()
			},
			showJiAdmin(id) {
				this.cur_mechanism_id = id
				this.$refs.list_mechanism.open()
			},
			async getAllList() {
				let db = uniCloud.database()
				const responseTotal = await db.collection('mechanism').count()
				const size = responseTotal.result.total
				if (size > 0) {
					let total = size
					let processSize = 0
					let position = 1
					let allData = []
					while (processSize < total) {
						const responseData = await db.collection('mechanism')
							.field('_id as value,name as text')
							.skip(processSize).limit(500).get()
						if (responseData.result.data.length > 0) {
							responseData.result.data.forEach((e) => {
								e.indexId = position++
								allData.push(e)
							})
						}
						processSize += responseData.result.data.length
					}
					this.copyList = allData
					let temp =  [] 
					for (let s of this.copyList) {
						temp.push(s)
					}
					
					this.mechanismList = temp
				}
			},
			close() {
				this.$emit('onClose')
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
					uni.showToast({
						title: '修改成功'
					})
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
				uni.showLoading({
					mask: true
				})
				db.collection(dbCollectionName).doc(id).field(
					"name,parent_id,mobile,note,area,create_time,common,tel,address,start_time,end_time,status,update").get().then((
					res) => {
					const data = res.result.data[0]
					if (data) {
						this.formData = data
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
				})
			}
		}
	}
</script>
<style>
	.uni-button-group button{
		margin: 6px;
	}
</style>
